<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 2017-10-12
 * Time: 17:06
 */

namespace app\src\sunsun\common\helper;


use app\src\base\helper\ResultHelper;
use app\src\base\logic\BaseLogic;
use GatewayClient\Gateway;
use sunsun\po\BaseReqPo;

class DeviceInfoPollHelper
{

    public static function poll($deviceInfo, BaseReqPo $req, BaseLogic $logic)
    {
        $now = time();
        $did = $deviceInfo['did'];
        //设备信息2s以内如果更新过了，则不请求获取设备状态
        if (!empty($deviceInfo['tcp_client_id']) && $deviceInfo['tcp_last_send_time'] < $now - 1) {
            $req->setSn(SnHelper::getSn());
            // ============START 用于统计网络延时=========
            $session = Gateway::getSession($deviceInfo['tcp_client_id']);
            Gateway::updateSession($deviceInfo['tcp_client_id'], DelayStaticsHelper::init($session, $req));
            // ============END  用于统计网络延时==========
            $ret = self::sendReqToClient($did, $req->toDataArray(), $logic);

            if ($ret['status']) {
                // 只有成功后才更新该时间
                $logic->save(['did' => $did], ['tcp_last_send_time' => $now]);
            }
        }
    }

    protected static function sendReqToClient($did, $data, BaseLogic $logic)
    {
        if (empty($data)) {
            return ResultHelper::error('不能发送空数据');
        }

        $ret = SunsunEncodeHelper::encode($did, $data, $logic);
        if ($ret['status']) {
            $ret = self::sendToClient($did, $ret['info']);
        }
        return $ret;
    }

    protected static function sendToClient($did, $msg)
    {
        if (empty($msg)) {
            return ResultHelper::error('不能发送空数据');
        }
        try {
            if (!empty($tcp_client_id)) {
                Gateway::sendToClient($tcp_client_id, $msg);
            } else {
                Gateway::sendToUid($did, $msg);
            }
        } catch (\Exception $ex) {
            return ResultHelper::error('通讯异常，请重试');
        }
        return ResultHelper::success('发送成功');
    }
}